<script lang="ts" setup>
import type { FormItemRule } from 'element-plus'
import type { OptionsType, PlusColumn } from 'plus-pro-components'

import { useGetProductBrand, useGetProductCategory, useGetProductCertificate, useGetProductInfo, useGetProductReport } from '@fl/api/supplier'
import { SearchForm } from '@fl/components'
import FlUpload from '@fl/components/fl-upload.vue'
import { useMessage } from '@fl/hooks/web/use-message'
import { Editor } from '@fl/origin-components/Editor/index'
import { cloneDeep } from 'lodash-es'

import editProperties from './edit-properties.vue'

const { createConfirmModal, createMessage } = useMessage()
const fileList = ref<any[]>([])
const { query } = useRoute()
const router = useRouter()
const activeName = ref(1)

const tabList = ref([
    {
        label: '产品信息',
        value: 1,
    },
    {
        label: '规格属性',
        value: 2,
    },
])
const form = ref()
const brandParams = computed(() => ({
    brandName: '',
    brandStatus: 1,
}))

const certificateParams = computed(() => ({ needValid: true }))
const reportParams = computed(() => ({}))
const { data: productCategory, isLoading: productCategoryLoading } = useGetProductCategory()
const { data: productBrandList, isLoading: productBrandListLoading } = useGetProductBrand(brandParams)
const { data: productCertificateList, isLoading: productCertificateListLoading } = useGetProductCertificate(certificateParams)
const { data: productReportList, isLoading: productReportLoading } = useGetProductReport(reportParams)
const { data: productInfo, isLoading: productInfoLoading } = useGetProductInfo(query?.id)
const isPending = computed(() => productCategoryLoading.value || productBrandListLoading.value || productCertificateListLoading.value || productInfoLoading.value || productReportLoading.value)

type IState = {
    id?: string
    isShow?: number | string
    productBrandId?: number | string
    productCategoryId?: string
    productCertificationId?: number | string
    productDetail?: string
    productHighlights?: string
    productImage?: string
    productModel?: string
    productName?: string
    productPurchaseConditions?: string
    productReportId?: number | string
    productUnit?: string
}

const initialState = {
    id: '',
    isShow: 1,
    productBrandId: '',
    productCategoryId: '',
    productCertificationId: '',
    productDetail: '',
    productHighlights: '',
    productImage: '',
    productModel: '',
    productName: '',
    productPurchaseConditions: '',
    productReportId: '',
    productUnit: '',
}
const state = ref<IState>(cloneDeep(initialState))
const detail = ref<any>({})

const brandRecords = ref()
const certificateRecords = ref()
const reportRecords = ref()
watchEffect(() => {
    if (productBrandList.value) {
        brandRecords.value = productBrandList.value.map(x => ({ label: x.brandName, value: x.id }))
    }

    if (productCertificateList.value) {
        certificateRecords.value = productCertificateList.value.map(x => ({ label: x.certificateName, value: x.id }))
    }

    if (productReportList.value) {
        reportRecords.value = productReportList.value.map(x => ({ label: x.reportName, value: x.id }))
    }

    if (productInfo.value) {
        detail.value = productInfo.value
        state.value = {
            id: productInfo.value.productVO.id,
            isShow: productInfo.value.productVO.isShow,
            productBrandId: productInfo.value.productVO.productBrandId,
            productCategoryId: productInfo.value.productVO.productCategoryId,
            productCertificationId: productInfo.value.productVO.productCertificateId,
            productDetail: productInfo.value.productVO.productDetail,
            productHighlights: productInfo.value.productVO.productHighlights,
            productImage: productInfo.value.productVO.productImage,
            productModel: productInfo.value.productVO.productModel,
            productName: productInfo.value.productVO.productName,
            productPurchaseConditions: productInfo.value.productVO.productPurchaseConditions,
            productReportId: productInfo.value.productVO.productReportId,
            productUnit: productInfo.value.productVO.productUnit,
        }
        fileList.value = productInfo.value.productVO.productImage ? productInfo.value.productVO.productImage.split(';').map(x => ({ url: x })) : []
    }
})

function validateProductName(_rule: FormItemRule, value: string, callback: Fn): void {
    const pattern = /\s/
    if (!value) {
        callback(new Error('请输入产品名称'))
    }
    if (pattern.test(value))
        callback(new Error('产品名称不允许输入空格'))

    else
        callback()
}

const rules = {
    productCategoryId: [
        {
            message: '请选择产品类目',
            required: true,
        },
    ],
    productImage: [
        {
            message: '请上传产品图片',
            required: true,
        },
    ],
    productModel: [
        {
            message: '请输入产品型号',
            required: true,
        },
    ],
    productName: [
        {
            required: true,
            trigger: ['blur', 'change'],
            validator: validateProductName,
        },
    ],
    productUnit: [
        {
            message: '请输入计量单位',
            required: true,
        },
    ],
}

const disabledFieldProps = computed(() => {
    return {
        disabled: !!query.id,
        props: { children: 'children', emitPath: false, label: 'categoryName', value: 'id' },
    }
})

const columns: PlusColumn[] = [
    {
        fieldProps: disabledFieldProps,
        label: '产品类目',
        options: productCategory as OptionsType,
        prop: 'productCategoryId',
        valueType: 'cascader',
    },
    {
        fieldProps: {
            maxlength: 100,
        },
        label: '产品名称',
        prop: 'productName',
    },
    {
        label: '产品型号',
        prop: 'productModel',
    },
    {
        label: '购买条件',
        prop: 'productPurchaseConditions',
    },
    {
        fieldProps: { clearable: true, filterable: true },
        label: '选择品牌',
        options: brandRecords as OptionsType,
        prop: 'productBrandId',
        valueType: 'select',

    },
    {
        label: '计量单位',
        prop: 'productUnit',
    },
    {
        fieldProps: { clearable: true, filterable: true },
        label: '产品证书',
        options: certificateRecords as OptionsType,
        prop: 'productCertificationId',
        valueType: 'select',
    },
    {
        fieldProps: { clearable: true, filterable: true },
        label: '产品报告',
        options: reportRecords as OptionsType,
        prop: 'productReportId',
        valueType: 'select',
    },
    {
        label: '是否上架展示',
        options: [
            {
                label: '是',
                value: 1,
            },
            {
                label: '否',
                value: 0,
            },
        ],
        prop: 'isShow',
        valueType: 'radio',
    },
    {
        colProps: {
            span: 24,
        },
        fieldProps: {
            autosize: { maxRows: 5, minRows: 3 },
        },
        label: '产品亮点',
        prop: 'productHighlights',
        valueType: 'textarea',
    },
    {
        colProps: {
            span: 24,
        },
        label: '产品图片',
        prop: 'productImage',

    },
    {
        colProps: {
            span: 24,
        },
        label: '产品详情图',
        prop: 'productDetail',
    },

]

async function next() {
    if (!productCategory.value.length) {
        createMessage.warning('请先去企业管理完善企业信息产品服务类别')
        return
    }
    const valid = await form.value.formInstance.formInstance.validate()
    if (valid) {
        createConfirmModal({ content: '请确认当前填写的产品信息，一旦点击下一步就无法更改？', onError: () => {
            console.log('操作取消！')
        }, onSuccess: () => {
            console.log(state.value)
            activeName.value = 2
        } })
    }
}

function goback() {
    fileList.value = []
    router.push('/supplier-pages/product-management/list')
}
</script>

<template>
    <ElCard shadow="never"
            class="mb-10"
    >
        <div class="mb-20 text-24 font-500">
            {{ query.id ? '编辑产品' : '新增产品' }}
        </div>

        <div class="tab">
            <div v-for="item in tabList"
                 :key="item.value"
                 class="tabItem"
                 :class="{ active: activeName === item.value }"
            >
                {{ item.label }}
            </div>
        </div>
    </ElCard>

    <ElCard v-if="activeName === 1"
            shadow="never"
    >
        <SearchForm ref="form"
                    v-model="state"
                    label-width="100px"
                    :rules="rules"
                    :columns="columns"
                    :has-footer="false"
        >
            <template #plus-field-productImage>
                <FlUpload :key="String(productInfoLoading)"
                          v-model="state.productImage!"
                          list-type="picture-card"
                          accept=".png,.jpg,.jpeg"
                          is-check-width-or-height
                          :limit="10"
                          split-symbol=";"
                          tips="商品主图尺寸要求宽度大于600或高度大于600"
                          :file-size="20"
                />
            </template>

            <template #plus-field-productDetail>
                <Editor v-model="state.productDetail"
                        :height="250"
                />
            </template>
        </SearchForm>

        <template #footer>
            <div class="flex justify-center">
                <el-button type="info"
                           @click="goback"
                >
                    返回
                </el-button>

                <el-button type="primary"
                           :loading="isPending"
                           @click="next"
                >
                    下一步
                </el-button>
            </div>
        </template>
    </ElCard>

    <editProperties v-else
                    v-model:detail="detail"
                    :product-info="state"
    />
</template>

<style lang="less" scoped>
:deep(.upload-demo) {
    i.el-icon--close-tip {
        display: none !important;
    }
}

.tab {
    width: 100%;
    border-bottom: 2px solid #e4e7ed;
    display: flex;

    .tabItem {
        height: 100%;
        font-size: 14px;
        font-weight: 500;
        color: #333;
        line-height: 20px;
        margin-right: 40px;
        position: relative;
        padding-bottom: 10px;

        &.active {
            color: #da0004;

            &::after {
                content: '';
                width: 100%;
                height: 2px;
                left: 0;
                bottom: -2px;
                background: #da0004;
                position: absolute;
            }
        }
    }
}
</style>
